<template>
  <div class="location">
    <div v-if="route.query.state === '设备'" class="breadcrumb">
      <a-breadcrumb>
        <a-breadcrumb-item>
          <a @click="toIndex">首页</a>
        </a-breadcrumb-item>
        <a-breadcrumb-item>
          <a @click="toGoto">信息发布</a>
        </a-breadcrumb-item>
        <a-breadcrumb-item> <a>编辑信息</a> </a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div v-else class="breadcrumb">
      <a-breadcrumb>
        <a-breadcrumb-item> <a @click="toIndex">首页</a> </a-breadcrumb-item>
        <a-breadcrumb-item>
          <a @click="toIndex">信息发布</a>
        </a-breadcrumb-item>
        <!-- <a-breadcrumb-item>
          <a @click="toGoto">编辑信息</a>
        </a-breadcrumb-item> -->
        <a-breadcrumb-item><a>编辑信息</a></a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div class="right-top">
      <div class="returns" @click="toBack(3)">
        <!-- <img src="@/assets/images/icon_back_arrow.png" alt="" /> -->
        <svg-icon class="icon-back-arrow" name="icon_back_arrow" :width="20" :height="20" />
        返回
      </div>
      <!-- 草稿箱修改；没有步骤 -->
      <div
        v-if="route.query.modify !== 'modify' && route.query.state !== '草稿箱发布'"
        class="step"
      >
        <div
          class="first"
          :class="stepValue * 1 === 1 ? 'step-active' : 'step-left'"
          @click="stepValue * 1 === 2 ? toBack(2) : null"
        >
          <div class="yuan">1</div>
          <div class="step-name">{{ setUpList[0] }}</div>
        </div>
        <div
          class="first"
          :class="stepValue * 1 === 2 ? 'step-active' : 'step-right'"
          @click="stepValue * 1 === 1 ? onPosition(8) : null"
        >
          <div class="yuan">2</div>
          <div class="step-name">{{ setUpList[1] }}</div>
        </div>
      </div>
      <div class="btns-lists">
        <a-button
          v-if="route.query.state === '设备'"
          class="to-next"
          type="primary"
          @click="onPosition(8)"
        >
          下一步
        </a-button>
        <template v-else>
          <a-button
            v-if="route.query.state !== '草稿箱编辑' && route.query.state !== '草稿箱发布'"
            class="time-send mg-right16"
            @click="toBack(2)"
          >
            上一步
          </a-button>
          <template v-if="timing">
            <a-button
              v-if="route.query.state !== '设备'"
              class="time-send no-mg-right"
              @click="onPosition(2)"
            >
              定时发布
            </a-button>
          </template>
          <a-button
            v-if="route.query.state !== '设备'"
            class="send"
            type="primary"
            @click="onPosition(1)"
          >
            立即发布</a-button
          >
        </template>
      </div>
    </div>
    <Card class="card">
      <div class="button-bx">
        <div class="pattern">
          <div
            :class="patternState === 0 ? 'pattern-active' : null"
            class="pattern-li"
            @click="patternStateClick(0)"
          >
            普通模式
          </div>
          <div
            :class="patternState === 1 ? 'pattern-active' : null"
            class="pattern-li"
            @click="patternStateClick(1)"
          >
            霸屏模式
          </div>
        </div>
      </div>
      <!-- 中间 -->
      <div class="change">
        <div class="change-left">
          <div class="type-tabs">
            <template v-for="item in deviceTypeTabs" :key="item.id">
              <div
                class="tabs-name"
                :class="[item.id === activeKey ? 'tab-active' : null]"
                @click="changTabs(item)"
              >
                {{ item.name }}
              </div>
            </template>
          </div>
          <div v-if="activeKey * 1 === 1" class="classs">
            <a-radio-group v-model:value="equipmentTypeValue">
              <Empty v-if="deviceType.length === 0" class="no-listo" :image="simpleImage" />
              <div
                v-for="(item, index) in deviceType"
                :key="item.infoId"
                class="change-type"
                :class="equipmentTypeValue === item.deviceTypeId ? 'change-type-active' : null"
              >
                <a-radio
                  v-model:value="item.deviceTypeId"
                  @change="equipmentTypeChange(index, $event, item.positionType)"
                  >{{ item.typeName }}
                </a-radio>
              </div>
            </a-radio-group>
          </div>
          <div v-if="activeKey * 1 === 2" class="classs">
            <Empty v-if="treeData.length === 0" class="no-listo" :image="simpleImage" />
            <a-tree
              v-else
              v-model:expandedKeys="expandedKeys"
              v-model:selectedKeys="selectedKeys"
              v-model:checkedKeys="checkedKeys"
              checkable
              class="trees"
              :tree-data="treeData"
              @expand="onExpand"
              @select="onSelect"
              @check="onCheck"
            />
          </div>
          <div v-if="activeKey * 1 === 3 && patternState !== 1" class="classs">
            <div v-if="TypeinfoType === 3 || TypeinfoType === ''" class="name">泉城e学</div>
            <Empty v-else :image="simpleImage" class="no-list" />
          </div>
        </div>
        <!-- 设备 -->
        <div v-if="activeKey !== '3'" class="equipment-module">
          <div class="head">
            <div class="left-tip"></div>
            <div class="content-title">设备(必选)</div>
            <div style="margin-left: auto">
              <a-input
                v-model:value="deviceNames"
                placeholder="请输入设备名称"
                class="search-input"
                @change="searchDevice(equipmentTypeValue, 'change')"
                @keyup.enter="searchDevice(equipmentTypeValue)"
              >
                <template #prefix>
                  <i class="ifont-wid-icon_search" :class="'icons'" style="color: #c2c2c2"></i>
                </template>
              </a-input>
            </div>
          </div>
          <div class="device device-title">
            <div class="checkbox">
              <a-checkbox
                :checked="isAllChecked"
                :indeterminate="indeterminate"
                @change="onSelectAll"
              >
                <div class="equipment-li">
                  <div class="title all-title"> 全选 </div>
                  <div class="title postion-title"> 所在位置</div>
                  <div class="title class-title"> 所在班级</div>
                  <div class="equipment-state-list"> 状态 </div>
                </div>
              </a-checkbox>
            </div>
          </div>
          <div class="equipment-scrollbar">
            <Empty v-if="equipmentList.length === 0" class="no-list" :image="simpleImage" />
            <a-radio-group v-else v-model:value="equipmentValue" class="margin-t">
              <div
                v-for="(item, index) in equipmentList"
                :key="index"
                class="device"
                :class="item.checked === true ? 'active' : null"
              >
                <Popover
                  :get-popup-container="
                    triggerNode => {
                      return triggerNode.parentNode || document.body;
                    }
                  "
                  trigger="hover"
                >
                  <template #content>
                    <div>设备名称：{{ item.deviceName }}</div>
                    <div>所在位置：{{ item.locationName }}</div>
                    <div>所属班级：{{ item.clazzName }}</div>
                    <div v-if="patternState === 0">
                      功能模块：
                      <span v-for="(items, index) in item.moduleVOList" :key="items.id">
                        {{ items.configName }}
                        <span v-if="index !== item.moduleVOList.length - 1">、</span>
                      </span>
                    </div>
                    <div>
                      支持文件格式：
                      <span>{{ moduleTypes(item.moduleVOList) }}</span>
                    </div>
                    <div class="last-state">
                      <span>状态：</span>
                      <span v-if="item.onlineStatus === 0" class="equipment-state">
                        <span class="identificationa"></span>
                        <span>离线</span>
                      </span>
                      <span v-else-if="item.onlineStatus === 1" class="equipment-state">
                        <span class="identificationb"></span>
                        <span>在线</span>
                      </span>
                      <span v-else class="equipment-state-false">
                        <span class="identification"></span>
                        <span>故障</span>
                      </span>
                    </div>
                  </template>
                  <div class="checkbox">
                    <a-checkbox
                      v-model:value="item.checked"
                      :checked="item.checked"
                      @change="equipmentCheckbox(item, index, $event, item.positionId)"
                    >
                      <div class="equipment-li">
                        <div class="title all-title"> {{ item.deviceName }}</div>
                        <div class="title postion-title">
                          {{ item.locationName }}
                        </div>
                        <div class="title class-title">
                          {{ item.clazzName }}
                        </div>
                        <div class="equipment-state-list">
                          <span v-if="item.onlineStatus === 0" class="equipment-state">
                            <span class="identificationa"></span>
                            <span>离线</span>
                          </span>
                          <span v-else-if="item.onlineStatus === 1" class="equipment-state">
                            <span class="identificationb"></span>
                            <span>在线</span>
                          </span>
                          <div v-else class="equipment-state-false">
                            <span class="identification"></span>
                            <span class="state">故障</span>
                          </div>
                        </div>
                      </div>
                    </a-checkbox>
                  </div>
                </Popover>
              </div>
            </a-radio-group>
          </div>
        </div>
        <!-- 功能模块 -->
        <div>
          <div v-if="activeKey === '3'" class="change-right">
            <div class="head">
              <div class="left-tip"></div>
              <div class="content-title">功能模块</div>
            </div>
            <template v-if="TypeinfoType === 3 || TypeinfoType === ''">
              <div class="name">通知公告</div>
            </template>
            <Empty v-else :image="simpleImage" style="margin-top: 170px !important" />
          </div>
          <div v-if="equipmentValue.length !== 0" class="change-right">
            <div class="head">
              <div class="left-tip"></div>
              <div class="content-title">
                功能模块<span v-if="patternState === 0">（必选）</span>
              </div>
            </div>
            <Empty v-if="funcModules.length === 0" class="no-list" :image="simpleImage" />
            <div v-else class="gn-module-box">
              <div
                v-for="(em, index) in funcModules"
                :key="index"
                class="functional-module"
                :class="em.checked === true ? 'actived' : null"
              >
                <a-checkbox
                  v-model:value="em.checked"
                  :checked="em.checked"
                  @change="onModule(index, $event, em)"
                >
                  <div class="mokuai-box">
                    <div class="mokuai-name">{{ em.name }}</div>
                    <div v-if="em.widgetId === 13" class="modul-class">
                      <div>视频：MP4</div>
                      <div class="modul-class">图片：JPG、JPEG、PNG</div>
                    </div>
                    <div v-else class="modul-class"> 富文本</div>
                  </div>
                </a-checkbox>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Card>
  </div>
  <!-- 下一步弹窗 -->
  <my-dialog
    :dialog-state="dialog.visible"
    :dialog-title="dialog.title"
    :dialog-width="dialog.width"
    :icon-type="dialog.default"
    :footer="activeTabs === '1' ? false : true"
    :btn-title="dialog.btnTitle"
    :but-status="dialog.butStatus"
    :other-btn="true"
    :btn-state="dialog.btnState"
    @handleCancel="dialogCancel"
    @handleOk="handleOk"
    @handleOther="handleOther"
  >
    <template #location>
      <a-tabs v-model:activeKey="activeTabs" @change="getDataFn">
        <a-tab-pane key="1" tab="立即创作">
          <div
            v-for="(item, index) in toWhereTist"
            :key="item.id"
            class="information-class"
            @click="toContent(index)"
          >
            <img :src="item.img" alt="" />
            <div>
              <div class="names">{{ item.name }}</div>
              <div class="title">{{ item.title }}</div>
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane key="2" tab="使用草稿箱内容" force-render>
          <div class="draft-list">
            <a-back-top />
            <div
              v-for="(item, index) in draftsData"
              :key="item.id"
              class="draft"
              :class="(index + 1) % 3 === 0 ? 'drafts' : null"
            >
              <video
                v-if="
                  item.infoType === 1 &&
                  item.thumbnailUrl.substr(item.thumbnailUrl.length - 1, 1) === '4'
                "
                class="cover"
                :src="item.thumbnailUrl"
                :class="item.checked ? 'actives' : null"
                @click="toDrafts(item, index)"
              >
              </video>
              <img
                v-else
                :src="item.thumbnailUrl"
                alt=""
                class="cover"
                :class="item.checked ? 'actives' : null"
                @click="toDrafts(item, index)"
              />
              <div class="draft-bottom">
                <!-- 文档infoType ==2 -->
                <img v-if="item.infoType === 2" src="../../assets/images/aa2px.png" alt="" />
                <!-- 组图infoType ==1 -->
                <img
                  v-else-if="item.infoType === 1"
                  src="../../assets/images/diagram@2x.png"
                  alt=""
                />
                <!-- 文章infoType ==3 -->
                <img
                  v-else-if="item.infoType === 3"
                  src="../../assets/images/popup_icon_content.png"
                  alt=""
                />
                <!-- 视频infoType ==0 -->
                <img v-else src="../../assets/images/video@2x.png" alt="" />
                <div :title="item.infoName" class="info-name">{{ item.infoName }}</div>
              </div>
            </div>
            <Empty v-if="draftsData.length === 0" :image="simpleImage" class="no-lists" />
          </div>
          <!-- 分页 -->
          <div v-if="draftsData.length !== 0" class="pagination">
            <a-pagination
              v-model:pageSize="pageSize"
              v-model:current="current"
              show-quick-jumper
              :show-size-changer="true"
              :total="total"
              @change="paginationChange"
            />
          </div>
        </a-tab-pane>
      </a-tabs>
    </template>
  </my-dialog>
  <!-- 发布设置弹窗 -->
  <my-dialog
    :dialog-state="publishDialog.visible"
    :dialog-title="publishDialog.title"
    :dialog-width="publishDialog.width"
    :icon-type="publishDialog.default"
    :but-status="publishDialog.butStatus"
    @handleCancel="publishDialogCancel"
    @handleOk="publishDialogOk"
  >
    <template #location>
      <div class="time">
        <div class="tips">*</div>
        <div>发布时长：</div>
        <a-range-picker
          v-model:value="publishTime"
          :disabled-time="disabledDateTime"
          format="YYYY-MM-DD HH:mm"
          show-time
          :disabled-date="disabledDate"
          :disabled="[true, permanentChecked ? true : false]"
          @change="selsectTime"
          @openChange="openChange"
          @ok="ok"
          @calendarChange="timeFn = '0天0时0秒'"
        />
      </div>

      <div v-if="permanentChecked" class="time-slot">永久</div>
      <div v-else class="time-slot">{{ timeFn }}</div>
      <div class="permanent-switch">
        <div class="permanent">永久发布：</div>
        <a-switch v-model:checked="permanentChecked" @change="isForeverChange" />
      </div>
    </template>
  </my-dialog>
  <!-- 定时发布 -->
  <regular-release-dialog
    ref="regularReleaseChild"
    :regular-release="regularRelease.visible"
    :timing-data="timingData"
    :timing-state="timingState"
    @handleCancel="regularReleaseCancel"
    @handleOks="regularReleaseOk"
  ></regular-release-dialog>
  <!-- 离线提示弹窗 -->
  <my-dialog
    :dialog-state="offLineDialog.visible"
    :dialog-title="offLineDialog.title"
    :dialog-width="offLineDialog.width"
    :icon-type="offLineDialog.default"
    :but-status="offLineDialog.butStatus"
    :btn-title="offLineDialog.btnTitle"
    :determine-btn="offLineDialog.determineBtn"
    :other-btn="true"
    :btn-state="offLineDialog.btnState"
    @handleOther="offLineHandleOther"
    @handleCancel="offLineDialogCancel"
    @handleOk="offLineDialogOk"
  >
    <template #location>
      <div class="content">
        <i :class="'icon-warring'" class="icon"></i>
        <span class="text">以下设备存在故障，处于离线状态</span>
      </div>
      <div class="off-line-equipment-list">
        <div v-for="(item, index) in outPositionBOList" :key="item.id" class="off-line-equipment">
          <Popover
            :get-popup-container="
              triggerNode => {
                return triggerNode.parentNode || document.body;
              }
            "
            trigger="hover"
          >
            <template #content>
              <div>{{ item.name }}</div>
            </template>
            <div class="equipment-name">{{ item.name }}</div>
          </Popover>
          <div class="equipment-state">
            <div class="line"></div>
            离线
          </div>
          <div class="equipment-choice" @click="choiceEquipment(index, item.positionId, '离线')"
            >取消选择</div
          >
        </div>
      </div>
      <div class="button-tips">
        【继续发布】将跳过离线设备发布信息，离线设备上线后同步展示发布内容。
      </div>
    </template>
  </my-dialog>
  <!-- 发布提示弹窗 -->
  <my-dialog
    :dialog-state="publishTipsDialog.visible"
    :dialog-title="publishTipsDialog.title"
    :dialog-width="publishTipsDialog.width"
    :icon-type="publishTipsDialog.default"
    :but-status="publishTipsDialog.butStatus"
    :btn-title="publishTipsDialog.btnTitle"
    :determine-btn="publishTipsDialog.determineBtn"
    :other-btn="true"
    class="publish-tips-dialog"
    :btn-state="publishTipsDialog.btnState"
    @handleOther="publishTipsDialogOther"
    @handleCancel="publishTipsDialogCancel"
    @handleOk="publishTipsDialogOk"
  >
    <template #location>
      <div class="publish-scrollbar">
        <div class="content">
          <div class="content-left">
            <i :class="'icon-warring'" class="icon"></i>
            <span class="text">继续发布将覆盖正在发布信息的部分时段</span>
          </div>
          <div class="tipss"> （设备在所选时间内正在展示以下信息） </div>
        </div>
        <div class="off-line-equipment-list">
          <a-table :data-source="conflictDevice" :columns="columns">
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'equipmentName'">
                {{ record.equipmentName }}
              </template>
              <template v-else-if="column.dataIndex === 'model'">
                <div v-if="record.conflict === 0" class="equipment-choices">霸屏模式</div>
                <div v-else class="equipment-choicess">全屏模式</div>
              </template>
              <template v-else-if="column.dataIndex === 'releaseUserName'">
                {{ record.releaseUserName ? record.releaseUserName : '--' }}
              </template>
              <template v-else-if="column.dataIndex === 'releaseName'">
                {{ record.releaseName }}
              </template>
              <template v-else>
                <div
                  class="equipment-choice"
                  @click="choiceEquipment(index, record.equipmentId, '冲突')"
                  >取消选择</div
                >
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </template>
  </my-dialog>
  <div v-if="loading" class="loading">
    <Spin class="loadings"></Spin>
    <!-- tip="更多内容加载中" -->
  </div>
</template>
<script>
export default {
  name: 'postion'
};
</script>
<script setup scoped>
import MyDialog from '@/components/dialog/index.vue';
import { Card, Tabs, Message, Popover, Spin, Breadcrumb, Empty } from 'ant-design-vue';
import moment from 'moment';
import { reactive, ref, onMounted, computed } from 'vue';
import regularReleaseDialog from '@/components/regularReleaseDialog/index.vue'; // 定时发布弹窗
import {
  hasApplicationPermission,
  getInfoArticle,
  getInfoImage,
  updateInfoArticle,
  saveInfoArticle,
  saveInfoImage,
  updateInfoImage,
  checkCollide,
  getListDeviceType,
  getDeviceListByDeviceTypeId,
  getClassList,
  devicePermissionsList,
  getDeviceByClassIds
} from '@/api/user';
import { getReleaseInfoList } from '@/api/post-list';
import { useRouter, useRoute } from 'vue-router';
import dayjs from 'dayjs';
import { defaultFengmian, getEscapeUrl, timeFns, columns } from '@/util/OBSUpload';
import { articleId, infoImageId, moduleTypes, getFromRouteInfo } from '@/util/utils';
import { useStore } from 'vuex';
const store = useStore();
let activeKeys = ref('');
const TypeinfoType = ref('');
let routeQueryData = ref([]); // 路由query.data
let postionData = ref([]); // 缓存位置信息参数
let informationData = ref([]); // 缓存发布数据信息参数
let identity = ref(8); // 管理员身份
onMounted(() => {
  identity.value = localStorage.getItem('identity');
  console.log('位置信息页面-路由参数', route.query);
  if (localStorage.getItem('postionData')) {
    postionData.value = JSON.parse(localStorage.getItem('postionData'));
    console.log('缓存位置信息参数', postionData.value);
  }
  console.log(666, localStorage.getItem('informationData'));
  if (localStorage.getItem('informationData')) {
    informationData.value = JSON.parse(localStorage.getItem('informationData'));
    console.log('缓存发布数据信息参数', informationData.value);
  }
  if (route.query.state === '草稿箱发布') {
    editData();
    TypeinfoType.value = route.query.infoType * 1;
  } else {
    if (route.query.state !== '设备') {
      //  1图像 2文档 3文章
      TypeinfoType.value = route.query.releaseType * 1 === 4 ? 3 : 1;
    }
  }
  if (route.query.state === '设备') {
    setUpList.value = ['发布位置', '内容编辑'];
    stepValue.value = 1;
  } else {
    setUpList.value = ['内容编辑', '发布位置'];
    stepValue.value = 2;
  }
  if (route.query.state === '编辑') {
    let params = postionData.value;
    patternState.value = params.infoBO.pattern;
    params.oldPositionBOList.forEach(item => {
      if (item.positionType === 1) {
        activeKeys.value = '1';
        equipmentTypeValue.value = params.oldPositionBOList[0].equipmentTypeId;
        equipmentName.value = params.oldPositionBOList[0].equipmentTypeName;
        equipmentId.value = params.oldPositionBOList[0].equipmentTypeId;
      } else {
        activeKey.value = '3';
        timing.value = false;
      }
    });
  }
  getDeviceType(); // 设备类型接口
  getApplicationPlatform(); // 获取泉城e学权限
});

let setUpList = ref(['内容编辑', '发布位置']);
let stepValue = ref(1); // 步骤选中值
let deviceTypeTabs = ref([
  { name: '设备类型', id: '1' },
  { name: '班级', id: '2' },
  { name: '应用平台', id: '3' }
]);
// 半全选
let isAllChecked = ref(false);
let indeterminate = ref(false); //  半全选状态
let patternState = ref(0); // 模式 0：普通模式；1：霸屏模式
function patternStateClick(value) {
  patternState.value = value;
  if (value * 1 === 1) {
    deviceTypeTabs.value = [
      { name: '设备类型', id: '1' },
      { name: '班级', id: '2' }
    ];
  } else {
    getApplicationPlatform(); // 获取泉城e学权限
  }
  getDeviceType();
  indeterminate.value = false;
  isAllChecked.value = false;
  activeKey.value = '1';
  setTimeout(() => {
    equipmentList.value.forEach(item => {
      item.checked = false; // 设备取消选中
    });
    funcModules.value = []; //  清空模块
    equipmentValue.value = [];
    moduleValue.value = [];
  }, 100);
}
let loading = ref(false); // loding
let expandedKeys = ref([]); // 默认展开
let selectedKeys = ref([]); // 当前被点击的节点
let checkedKeys = ref([]); // 当前复选框被选中的节点 父亲与儿子也在同一个数组 所有儿子被选中则父亲也被选中
let autoExpandParent = ref(false); // 是否自动展开父节点
let treeData = ref([]); // 班级数据
function onExpand(expandedKeys) {
  expandedKeys.value = expandedKeys;
}
let allClassId = ref([]); // 选中班级id
// 点击复选框触发
function onCheck(checkedKeys, e) {
  console.log(checkedKeys, e);
  if (checkedKeys.length === 0) {
    equipmentValue.value = [];
    listaa.value = [];
    dataDeviceId.value = [];
    equipmentList.value = [];
    indeterminate.value = false;
    isAllChecked.value = false;
    return;
  }
  checkedKeys.value = checkedKeys;
  // 获取已选中的班级id
  let classList = checkedKeys.filter(item => item.toString().length === 18);
  allClassId.value = classList;
  if (classList.length !== 0) {
    loading.value = true;
    deviceListByDeviceTypeIds(
      { ids: classList.join(','), applicationId: '2', pattern: patternState.value, deviceName: '' },
      '3'
    );
  }
}
// 获取 根据班级获取设备列表
function deviceListByDeviceTypeIds(classList, values) {
  if (identity.value * 1 === 8) {
    // 根据班级ids获取设备列表
    getDeviceByClassIds(classList).then(res => {
      if (res.data.code === 200) {
        console.log('这去');
        loading.value = false;
        getLocationDatas(res.data.data, values);
      }
    });
  } else {
    devicePermissionsList(classList).then(res => {
      console.log('这');
      if (res.data.code === 200) {
        loading.value = false;
        getLocationData(res.data.data, values);
      }
    });
  }
}
// 点击树节点触发
function onSelect(selectedKeys, info) {
  selectedKeys.value = selectedKeys;
}
// 暂无数据
const simpleImage = ref(require('../../assets/images/noData@2x.png'));
// 分页
const total = ref(0); // 总数
const pageSize = ref(6); // 每页数量
const current = ref(1); // 当前页
// 分页
function paginationChange(e) {
  current.value = e;
  releaseInfoList();
}
let draftsParams = ref({}); // 草稿箱参数
let draftsData = ref([]); // 草稿箱数据
// 草稿箱参数
let param = ref({
  size: '6',
  current: 1,
  identity: identity.value,
  data: {
    isDraft: 1, // 是否是草稿 0已发布 1草稿箱
    infoType: '' // 发布信息题材类型 0视频 1组图 2文档 3文章 (选择全部不用给这个字段传信息
  }
});
let timing = ref(true); // 定时发布按钮
// tab事件
function changTabs(e) {
  activeKey.value = e.id;
  equipmentValue.value = []; // 设备为空
  dataDeviceId.value = []; // 清空已选中的id
  deviceNames.value = [];
  allClassId.value = []; // 清空选中班级存储的id
  // 设备类型
  if (e.id === '1') {
    timing.value = true;
    listaa.value = [];
    getDeviceType(); // 获取类型
  }
  // 班级
  if (e.id === '2') {
    timing.value = true;
    getClass(); // 获取班级结构
    equipmentList.value = []; // 清空设备
    listaa.value = [];
    checkedKeys.value = []; // 清空已选中的班级
  }
  // 应用平台
  if (e.id === '3') {
    positionBOList.value = [];
    listaa.value = [];
    outPositionBOList.value = [];
    timing.value = false;
  }
  isAllChecked.value = false;
  indeterminate.value = false;
}
// 下一步tab change
function getDataFn(e) {
  if (e === '2') {
    current.value = 1;
    releaseInfoList();
  }
}
// 获取发布列表数据
function releaseInfoList() {
  console.log(activeTab.value);
  param.value.current = current.value;
  param.value.data.identity = identity.value;
  param.value.data.infoType = activeTab.value; // 区分视频还是文章登
  param.value.data.pattern = patternState.value;
  if (activeKey.value === '3' && activeTab.value === 3) {
    dialog.otherBtn = false;
    dialog.btnTitle = '';
  } else {
    dialog.otherBtn = true;
    dialog.btnTitle = '定时发布';
  }
  console.log(param.value);
  getReleaseInfoList(param.value).then(res => {
    let data = [];
    total.value = res.data.data.total;
    current.value = res.data.data.current;
    res.data.data.records.forEach(items => {
      //  1图像 2文档 3文章
      data.push({
        checked: false,
        id: items.id,
        infoName: items.infoName,
        infoType: items.infoType,
        thumbnailUrl: getEscapeUrl(items.thumbnailUrl, 'url'),
        releaseUserName: items.releaseUserName
      });
    });
    draftsData.value = data;
  });
}
//  去草稿箱 详情
function toDrafts(data, index) {
  draftsData.value.forEach(item => {
    item.checked = false;
  });
  draftsData.value[index].checked = true;
}
// 永久change
function isForeverChange() {
  if (permanentChecked.value) {
    publishTime.value = [
      dayjs(moment().format('YYYY-MM-DD HH:mm')),
      dayjs('9999-12-31 23:59', 'YYYY-MM-DD HH:mm')
    ];
  } else {
    publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
    timeFn.value = '0天0时0秒';
  }
  publishEndDate.value = '';
}
function toIndex() {
  closeData();
  router.push({
    path: '/'
  });
}
function closeData() {
  store.commit('removeCacheRoute', 'postion');
  store.commit('removeCacheRoute', 'postMessage');
  store.commit('removeCacheRoute', 'imgAndVideo');
  localStorage.removeItem('postionData'); // 清除位置信息
  localStorage.removeItem('informationData'); // 清除发布信息数据（图像， 文章）
}
function toGoto() {
  // 区分本地和基座内部，封装返回上一页方法
  if (window.__MICRO_APP_ENVIRONMENT__) {
    router.push(getFromRouteInfo());
  } else {
    router.go(-1);
  }

  closeData();
}
// 下一步弹窗相关
const dialog = reactive({
  title: '内容来源',
  default: 'default',
  visible: false,
  btnTitle: '定时发布',
  butStatus: '发布',
  btnState: '发布',
  width: '568px'
});
// 发布设置弹窗相关
const publishDialog = reactive({
  title: '发布设置',
  default: 'default',
  visible: false,
  butStatus: '确认发布',
  width: '545px'
});
// 离线弹窗
const offLineDialog = reactive({
  title: '设备离线提示',
  default: 'default',
  visible: false,
  determineBtn: true,
  btnState: '继续发布',
  btnTitle: '返回修改',
  width: '454px'
});
// 发布提示弹窗
const publishTipsDialog = reactive({
  title: '发布提示',
  default: 'default',
  visible: false,
  determineBtn: true,
  btnState: '继续发布',
  btnTitle: '返回修改',
  width: '832px'
});
const activeTabs = ref('1'); // tabs
const activeTab = ref(''); //
const toWhereTist = ref([]); // 发布类型数组(图像, 文章)
const tuxiangTitle = ref({
  name: '图像',
  id: 0,
  path: '/post-message/imgAndVideo',
  title: '用于发布jpg、jpeg、png、mp4类型信息。',
  img: require('../../assets/images/diagram@2x.png')
});
const wenzhangTitle = ref({
  name: '文章',
  id: 1,
  path: '/post-message/article',
  title: '用于发布富文本类型信息。',
  img: require('../../assets/images/popup_icon_content.png')
});
const route = useRoute();
let router = useRouter();
let editParams = ref({}); // 草稿箱发布获取模块参数

// 上一步
function toBack(params) {
  // params=2内容编辑（1步）;params=3 返回
  if (params * 1 === 2) {
    let data = JSON.stringify(positionBOList.value);
    localStorage.setItem('postionData', data);
    // 区分本地和基座内部，封装返回上一页方法
    if (window.__MICRO_APP_ENVIRONMENT__) {
      router.push(getFromRouteInfo());
    } else {
      router.go(-1);
    }
  } else {
    // 区分本地和基座内部，封装返回上一页方法
    if (window.__MICRO_APP_ENVIRONMENT__) {
      router.push(getFromRouteInfo());
    } else {
      router.go(-1);
    }
  }
}

/** *数据区域****/
let Base64 = require('js-base64').Base64;
let publishTime = ref([dayjs(moment().format('YYYY-MM-DD HH:mm')), '']); // 发布设置弹窗时间
let permanentChecked = ref(false); // 永久发布switch状态
let publishStartDate = ref(''); // 发布设置弹窗开始时间
let publishEndDate = ref(''); // 发布设置弹窗结束时间
const deviceType = ref([]); // 设备类型列表
const equipmentTypeValue = ref(''); // 设备类型value
const equipmentValue = ref([]); // 选中设备id
const moduleValue = ref([]); // 选中的功能模块id
const equipmentList = ref([]); // 设备列表
const funcModules = ref([]); // 功能模块列表
/** *方法区域****/
// 定时发布状态
let regularRelease = ref({ visible: false });
// 定时发布取消按钮
function regularReleaseCancel() {
  regularRelease.value.visible = false;
  if (route.query.state === '设备') {
    dialog.visible = true;
  }
}
// 当日只能选择当前时间之后的时间点
const range = (start, end) => {
  const result = [];
  for (let i = start; i <= end; i++) {
    result.push(i);
  }
  return result;
};
const newS = ref('');
const currentTimes = ref('');
// 禁止当前时间之前的时间不可选
const disabledDateTime = (dates, partial) => {
  if (dates != null) {
    newS.value = moment(dates.$d).format('YYYY-MM-DD'); // 选择的时间
    currentTimes.value = moment(dates.$d).format('YYYY-MM-DD HH'); // 选择的时间
  }
  let currentTime = moment().format('YYYY-MM-DD'); // 当前时间
  let hours = moment().hours(); // 0~23
  let minutes = moment().minutes(); // 0~59
  let seconds = moment().seconds(); // 0~59
  if ((dates === null && partial === 'end') || newS.value === currentTime) {
    return {
      disabledHours: () => range(0, hours - 1),
      disabledMinutes: () => (currentTimes.value.slice(-2) <= hours ? range(0, minutes) : null),
      disabledSeconds: () => range(0, seconds - 1)
    };
  }
};
function disabledDate(current) {
  //  禁用当前时间之前的时间
  return current && current < moment().subtract(1, 'days').endOf('days');
}
function getApplicationPlatform() {
  hasApplicationPermission()
    .then(res => {
      if (res.data.data) {
        deviceTypeTabs.value = [
          { name: '设备类型', id: '1' },
          { name: '班级', id: '2' },
          { name: '应用平台', id: '3' }
        ];
      } else {
        deviceTypeTabs.value = [
          { name: '设备类型', id: '1' },
          { name: '班级', id: '2' }
        ];
      }
    })
    .catch(() => {
      deviceTypeTabs.value = [
        { name: '设备类型', id: '1' },
        { name: '班级', id: '2' }
      ];
    });
}
const gradeList = ref([]);
// 获取班级结构
function getClass() {
  getClassList().then(res => {
    treeDatas(res.data.data);
    gradeList.value = res.data.data;
  });
}
function treeDatas(values) {
  console.log(values);
  let children = [];
  values.forEach((items, indexs) => {
    let childrenThree = [];
    if (items.children) {
      items.children.forEach(item => {
        let childrenTwo = [];
        childrenThree.push({
          title: item.schoolYear.toString(),
          key: item.gradeCode,
          children: childrenTwo
        });
        if (item.children) {
          item.children.forEach(ite => {
            childrenTwo.push({
              title: ite.className,
              gradeId: item.gradeCode,
              key: ite.businessId
            });
          });
        }
      });
    }
    children.push({
      title: items.sectionName,
      key: items.sectionCode,
      children: childrenThree
    });
    treeData.value = children;
  });
}
// 1.设备类型接口
function getDeviceType() {
  let paramss = {
    pattern: patternState.value, // ( 0普通模式 1霸屏模式);
    identity: identity.value
  };
  loading.value = true;
  getListDeviceType(paramss)
    .then(res => {
      if (res.data.code === 200) {
        loading.value = false;
        deviceType.value = res.data.data ? res.data.data : [];
        if (route.query.state === '编辑') {
          // let params = postionData.value;
        } else {
          equipmentTypeValue.value =
            deviceType.value.length !== 0 ? deviceType.value[0].deviceTypeId : null;
        }
        console.log(1111, equipmentTypeValue.value);
        if (equipmentTypeValue.value) {
          deviceListByDeviceTypeId(equipmentTypeValue.value); // 获取设备数据
        } else {
          equipmentList.value = []; // 设备清空
          funcModules.value = []; //  清空模块
        }
      }
    })
    .catch(err => {
      console.log(err);
      loading.value = false;
    });
}
// 2.设备类型change事件
function equipmentTypeChange(index, e, positionType) {
  equipmentValue.value = [];
  // equipmentList.value = []; // 清空设备
  deviceNames.value = '';
  equipmentTypeValue.value = deviceType.value[index].deviceTypeId;
  deviceListByDeviceTypeId(equipmentTypeValue.value);
  isAllChecked.value = false;
  indeterminate.value = false;
  dataDeviceId.value = []; // 清空已选中的id
}
// 搜索设备事件
function searchDevice(id, type) {
  loading.value = true;
  if (type === 'change') {
    setTimeout(() => {
      getSearchData(id);
    }, 100);
  } else {
    getSearchData(id);
  }
}
function getSearchData(id) {
  if (identity.value * 1 === 8) {
    getDeviceListByDeviceTypeId({
      deviceTypeId: activeKey.value === '1' ? id : null,
      ids: activeKey.value === '2' ? allClassId.value.join(',') : null,
      pattern: patternState.value, // ( 0普通模式 1霸屏模式);
      deviceName: deviceNames.value.replace(/\s+/g, ''),
      applicationId: '2'
    }).then(res => {
      loading.value = false;
      getLocationDatas(res.data.data);
      getDatas();
      setTimeout(() => {
        getAllChecked();
      }, 200);
    });
  } else {
    devicePermissionsList({
      ids: activeKey.value === '2' ? allClassId.value.join(',') : null,
      applicationId: '2',
      deviceTypeId: activeKey.value === '1' ? id : null,
      pattern: patternState.value, // ( 0普通模式 1霸屏模式);
      deviceName: deviceNames.value.replace(/\s+/g, '')
    }).then(res => {
      loading.value = false;
      getLocationDatas(res.data.data);
      setTimeout(() => {
        getAllChecked();
      }, 200);
    });
  }
}
function getAllChecked() {
  // 处理 全选
  let checkedData = [];
  console.log(555, equipmentList.value);
  equipmentList.value.forEach(item => {
    checkedData.push(item.checked);
  });
  console.log(4444, checkedData);
  let flag = false;
  let result = checkedData.every(item => item === flag);
  console.log(777, result);
  if (result) {
    indeterminate.value = false;
    isAllChecked.value = false;
  } else if (checkedData.indexOf(false) !== -1) {
    isAllChecked.value = false;
    indeterminate.value = true;
  } else {
    isAllChecked.value = true;
    indeterminate.value = false;
  }
  console.log(isAllChecked.value);
}
let deviceNames = ref(''); // 搜索设备名称
// 获得设备数据
function deviceListByDeviceTypeId(value) {
  // !==8普通成员
  loading.value = true;
  if (identity.value * 1 === 8) {
    // 管理员全部设备
    getDeviceListByDeviceTypeId({
      deviceTypeId: value,
      deviceName: '',
      applicationId: '2',
      pattern: patternState.value // ( 0普通模式 1霸屏模式);
    })
      .then(res => {
        loading.value = false;
        console.log(222, res.data.data);
        getLocationData(res.data.data);
      })
      .catch(() => {
        loading.value = false;
        equipmentList.value = [];
      });
  } else {
    devicePermissionsList({
      deviceTypeId: value,
      pattern: patternState.value,
      applicationId: '2',
      deviceName: ''
    })
      .then(res => {
        loading.value = false;
        console.log(444);
        getLocationData(res.data.data);
      })
      .catch(() => {
        loading.value = false;
        equipmentList.value = [];
      });
  }
}
function getLocationDatas(dataList, values) {
  patternState;
  let data = [];
  console.log('数据0909090他也0-他也0-让他有', dataList);
  dataList.forEach(item => {
    let isTrue = false;
    if (dataDeviceId.value.indexOf(item.deviceId) !== -1) {
      isTrue = true;
    }
    data.push({
      moduleVOList: item.moduleVOList ? item.moduleVOList : [],
      checked: isTrue,
      clazzId: item.clazzId,
      ...item
    });
  });
  console.log(44333, data);
  data.forEach(item => {
    if (route.query.releaseType) {
      item.moduleVOList = item.moduleVOList.filter(v => {
        if (route.query.releaseType * 1 === 13) {
          return v.id === 13;
        } else {
          return v.id === 4 || v.id === 11 || v.id === 12;
        }
      });
      data = data.filter(v => v.moduleVOList.length);
    }
    listaa.value.forEach(items => {
      if (items.checked) {
        if (item.deviceId === items.deviceId) {
          item.checked = true;
        }
      }
    });
  });
  equipmentList.value = data; // 设备数据 deviceId
  console.log(333, data);
  if (route.query.state === '编辑' && activeKeys.value === values) {
    let params = informationData.value;
    let outDatas = [];
    equipmentList.value.forEach(item => {
      params.oldPositionBOList.forEach(items => {
        if (items.positionId === item.deviceId) {
          item.checked = true;
        }
      });
      if (item.checked) {
        outDatas.push({
          onlineStatus: item.onlineStatus, // 离线状态
          name: item.deviceName,
          positionId: item.deviceId
        });
      }
    });
    outPositionBOList.value = outDatas; // 离线设备数据
    getDatas();
  }
}
function getLocationData(dataList) {
  let data = [];
  console.log('数据受到攻击的离开法国扣税的飞机螺丝钉', dataList);
  dataList.forEach(item => {
    data.push({
      clazzId: item.clazzId,
      moduleVOList: item.moduleVOList ? item.moduleVOList : [],
      checked: false,
      ...item
    });
  });
  data.forEach(item => {
    console.log(555, route.query.releaseType);
    if (route.query.releaseType) {
      if (route.query.releaseType * 1 === 4) {
        item.moduleVOList = item.moduleVOList.filter(v => v.id * 1 !== 13);
        data = data.filter(v => v.moduleVOList.length);
      } else {
        item.moduleVOList = item.moduleVOList.filter(v => v.id * 1 === route.query.releaseType * 1);
        data = data.filter(v => v.moduleVOList.length);
      }
    }
  });
  console.log('dfgdf', data);

  listaa.value = data;
  equipmentList.value = data; // 设备数据 deviceId
  // 开始遍历设备列表用 设备列表的deviceId跟缓存的positionId匹配如果相同就选中
  if (route.query.state === '编辑') {
    let params = postionData.value;
    console.log(54353453, params.oldPositionBOList);
    let outDatas = [];
    equipmentList.value.forEach(item => {
      params.oldPositionBOList.forEach(items => {
        if (items.positionId === item.deviceId) {
          console.log(item);
          item.checked = true;
        }
      });
      if (item.checked) {
        outDatas.push({
          onlineStatus: item.onlineStatus, // 离线状态
          name: item.deviceName,
          positionId: item.deviceId
        });
      }
    });
    outPositionBOList.value = outDatas; // 离线设备数据
    getAllChecked();
    getDatas();
  }
}
const dataDeviceId = ref([]);
// 全选
function onSelectAll(e) {
  console.log(333, e);
  isAllChecked.value = e.target.checked;
  let checked = [];
  equipmentList.value.forEach(item => {
    item.checked = e.target.checked;
    checked.push(item.checked);
  });
  if (indeterminate.value && checked.indexOf(true) !== -1) {
    indeterminate.value = false;
  }
  getDatass();
}
// 3.功能接口
function equipmentCheckbox(data, index, e, id) {
  console.log(333);
  data.checked = !data.checked;
  moduleValue.value = [];
  getDatass();
  if (e.target.checked) {
    dataDeviceId.value.push(data.deviceId);
  } else {
    dataDeviceId.value = dataDeviceId.value.filter(elem => elem !== data.deviceId);
  }
  console.log(44, equipmentList.value);
  // 处理 全选
  getAllChecked();
}
function getDatas() {
  console.log('getDatas');
  let modelId = [];
  let list = [];
  console.log(equipmentList.value, 88978);
  equipmentList.value.forEach((items, index) => {
    if (dataDeviceId.value.indexOf(items.deviceId) !== -1) {
      items.checked = true;
    }
    if (items.checked) {
      list.push({
        id: items.id,
        ...items
      });
      modelId.push(items.modelId);
    }
    equipmentValue.value = modelId;
  });
  console.log(list);
  let arrs = [];
  if (list.length > 1) {
    console.log(222);
    list[0].moduleVOList.forEach(e => {
      let compare = e.configId;
      let num = 0;
      for (let i = 1; i < list.length; i++) {
        // compare id判重
        if (JSON.stringify(list[i].moduleVOList)) {
          if (JSON.stringify(list[i].moduleVOList).indexOf(compare) > -1) {
            num += 1;
          }
        }
        if (i === list.length - 1) {
          // 循环到最后一次
          if (num === i) {
            arrs.push(e);
          }
        }
      }
    });
  } else {
    console.log(333);
    arrs = list.length === 0 ? [] : list[0].moduleVOList ? list[0].moduleVOList : [];
  }
  console.log(arrs, 8889898);
  let datas = [];
  arrs.forEach(item => {
    datas.push({
      configIds: item.configIds,
      widgetId: item.id,
      id: item.configId,
      name: item.configName,
      checked: item.checked ? item.checked : false
    });
  });
  console.log('out', outPositionBOList.value);
  if (outPositionBOList.value.length === 0) {
    datas.forEach(element => {
      element.checked = false;
    });
  }
  console.log(datas, '是多久发货');
  funcModules.value = datas;
  if (route.query.state === '编辑' && activeKeys.value === activeKey.value) {
    // 遍历缓存参数parentId与id匹配选中功能模块
    let params = postionData.value;
    console.log(55, params);
    params.oldPositionBOList.forEach(items => {
      funcModules.value.forEach(item => {
        if (item.id * 1 === (items.parentId * 1 || items.funcModule * 1)) {
          item.checked = true;
        }
      });
    });
    getEditData();
  }
  listaa.value = equipmentList.value;
  getPositionBOList();
}
function getEditData() {
  let id = [];
  let dataList = [];
  let outDatas = [];
  equipmentList.value.forEach(item => {
    if (item.checked) {
      if (item.onlineStatus === 0) {
        outDatas.push({
          onlineStatus: item.onlineStatus, // 离线状态
          name: item.deviceName,
          positionId: item.deviceId
        });
      }
    }
    funcModules.value.forEach(items => {
      if (items.checked) {
        id.push(items.funcModule);
      }
      moduleValue.value = id;
      if (items.checked) {
        if (item.checked) {
          dataList.push({
            widgetId: item.widgetId,
            positionType: activeKey.value === '3' ? 2 : 1, // 设备1，应用平台2
            equipmentTypeName: equipmentName.value,
            equipmentTypeId: equipmentId.value,
            name: item.deviceName,
            positionId: item.deviceId,
            funcModule: items.id,
            funcModuleName: items.name,
            uniqueId: item.uniqueId
          });
        }
      }
    });
  });
  outPositionBOList.value = outDatas; // 离线设备数据
  positionBOList.value = dataList; // 提示  ：注意这个数据的问题
}
function getDatass() {
  console.log(equipmentList.value);
  let modelId = [];
  let list = [];
  equipmentList.value.forEach((items, index) => {
    if (items.checked) {
      list.push({
        ...items
      });
      modelId.push(items.modelId);
    }
    equipmentValue.value = modelId;
  });
  console.log(6666, list);
  let arrs = [];
  if (patternState.value === 0) {
    // 普通模式
    if (list.length > 1) {
      list[0].moduleVOList.forEach(e => {
        let compare = e.configId;
        let num = 0;
        for (let i = 1; i < list.length; i++) {
          // compare id判重
          if (JSON.stringify(list[i].moduleVOList)) {
            if (JSON.stringify(list[i].moduleVOList).indexOf(compare) > -1) {
              num += 1;
            }
          }
          if (i === list.length - 1) {
            // 循环到最后一次
            // alert(num)
            if (num === i) {
              arrs.push(e);
            }
          }
        }
      });
    } else {
      arrs = list.length !== 0 ? (list[0].moduleVOList ? list[0].moduleVOList : []) : [];
    }
  } else {
    // 霸屏模式
    list.forEach(item => {
      item.moduleVOList.forEach(ite => {
        arrs.push(ite);
      });
    });
    console.log(666, arrs);
    arrs = quchong(arrs, 'configId');
  }
  console.log(3333, arrs);
  let datas = [];
  arrs.forEach(item => {
    datas.push({
      configIds: item.configIds,
      widgetId: item.id,
      id: item.configId,
      name: item.configName,
      checked: item.checked ? item.checked : false
    });
  });
  if (outPositionBOList.value.length === 0) {
    datas.forEach(element => {
      element.checked = false;
    });
  }
  console.log(55555555555, datas);
  funcModules.value = datas;
  if (route.query.state === '编辑' && activeKeys.value === activeKey.value) {
    let params = informationData.value;
    console.log(5555555555, params.oldPositionBOList);
    console.log(funcModules.value);
    params.oldPositionBOList.forEach(items => {
      funcModules.value.forEach(item => {
        if (item.id === items.funcModule * 1) {
          item.checked = true;
        }
      });
    });
  }
  listaa.value = equipmentList.value;
  getPositionBOList();
}
function quchong(dataList, id) {
  let res = []; // 去重复后的集合
  let tem = {};
  for (let i = 0; i < dataList.length; i++) {
    if (!tem[dataList[i][id]]) {
      res.push(dataList[i]);
      tem[dataList[i][id]] = 1;
    }
  }
  return res;
}
let equipmentName = ref();
let equipmentId = ref();
// 功能模块的对选事件
function onModule(index, e, data) {
  // console.log(777777, equipmentList.value);
  data.checked = !data.checked;
  let modelId = [];
  equipmentList.value.forEach(items => {
    if (items.checked) {
      modelId.push(items.modelId);
    }
    equipmentValue.value = modelId;
    items.moduleVOList.forEach(its => {
      its.checked = false;
    });
  });
  let id = [];
  funcModules.value.forEach(item => {
    if (item.checked) {
      id.push(item.id);
    }
    moduleValue.value = id;
  });
  console.log(deviceType.value, 999999, equipmentTypeValue.value);
  deviceType.value.forEach(item => {
    if (item.deviceTypeId === equipmentTypeValue.value) {
      equipmentName.value = item.typeName;
      equipmentId.value = item.deviceTypeId;
    }
  });
  equipmentList.value.forEach(items => {
    funcModules.value.forEach(item => {
      items.moduleVOList.forEach(its => {
        if (its.configId === item.id && item.checked) {
          its.checked = true;
        }
      });
    });
  });
  getPositionBOList();
}
// 获取PositionBOList funcModules.value: 模块数据（第三块）；equipmentList.value：设备数据（中间的）
let outPositionBOList = ref([]); // 离线设备数据
function getPositionBOList() {
  let datas = [];
  let outDatas = [];
  console.log(111, funcModules.value, equipmentList.value);
  equipmentList.value.forEach(item => {
    if (item.checked) {
      if (item.onlineStatus === 0) {
        outDatas.push({
          onlineStatus: item.onlineStatus, // 离线状态
          name: item.deviceName,
          positionId: item.deviceId
        });
      }
    }
    let id = [];
    funcModules.value.forEach(items => {
      // console.log(items, 9898989);
      if (items.checked) {
        id.push(items.id);
      }
      moduleValue.value = id;
    });
    if (patternState.value === 1 && moduleValue.value.length === 0) {
      // console.log(5555, funcModules.value);
      console.log(666, deviceType.value);
      deviceType.value.forEach(i => {
        if (i.deviceTypeId === equipmentTypeValue.value) {
          equipmentName.value = i.typeName;
          equipmentId.value = i.deviceTypeId;
        }
      });
      // 霸屏模式走这里， 进行处理新的数据与普通模式数据区分开
      if (item.checked) {
        datas.push({
          widgetId: 0, // 霸屏模式写死 0
          positionType: activeKey.value === '3' ? 2 : 1, // 设备1，应用平台2
          equipmentTypeName: equipmentName.value,
          equipmentTypeId: equipmentId.value,
          name: item.deviceName,
          positionId: item.deviceId,
          funcModule: 0, // 霸屏模式写死 0
          funcModuleName: 0, // 霸屏模式写死 0
          uniqueId: item.uniqueId
        });
      }
    } else {
      console.log(33);
      // 非霸屏 或者 新增的霸屏选择功能模块
      funcModules.value.forEach(items => {
        if (items.checked) {
          id.push(items.id);
          if (item.checked) {
            datas.push({
              configIds: items.configIds,
              widgetId: items.widgetId,
              positionType: activeKey.value === '3' ? 2 : 1, // 设备1，应用平台2
              equipmentTypeName: equipmentName.value,
              equipmentTypeId: equipmentId.value,
              name: item.deviceName,
              positionId: item.deviceId,
              funcModule: items.id,
              funcModuleName: items.name,
              uniqueId: item.uniqueId
            });
          }
        }
      });
    }
  });
  console.log(4444444, datas);
  positionBOList.value = datas; // 提示  ：注意这个数据的问题
  outPositionBOList.value = outDatas; // 离线设备数据
}
let listaa = ref([]);
let conflictData = ref([]); // 冲突设备数据
// 冲突弹唱取消
function choiceEquipment(index, id, type) {
  console.log(55555, index, id);
  let data = [];
  outPositionBOList.value.splice(index, 1);
  conflictDevice.value.splice(index, 1);
  dataDeviceId.value = dataDeviceId.value.filter(elem => elem !== id);
  positionBOList.value.forEach(item => {
    console.log(item);
    if (item.positionId !== id) {
      data.push({
        uniqueId: item.uniqueId,
        positionType: item.positionType,
        equipmentTypeName: item.equipmentTypeName,
        equipmentTypeId: item.equipmentTypeId,
        name: item.name,
        positionId: item.positionId,
        funcModule: item.funcModule,
        funcModuleName: item.funcModuleName
      });
    }
  });
  let checkedList = [];
  equipmentList.value.forEach(item => {
    if (item.deviceId === id) {
      item.checked = false;
      item.moduleVOList.forEach(itrems => {
        itrems.checked = false;
      });
    }

    checkedList.push(item.checked);
  });
  if (checkedList.indexOf(true) === -1) {
    funcModules.value = [];
  }
  if (type === '离线') {
    conflictData.value = data;
  } else {
    conflictData.value = conflictData.value.filter(items => {
      return items.positionId !== id;
    });
  }

  //
  if (conflictData.value.length === 0) {
    offLineDialog.determineBtn = false;
    publishTipsDialog.determineBtn = false;
  } else {
    publishTipsDialog.determineBtn = true;
    offLineDialog.determineBtn = true;
  }
  positionBOList.value.splice(index, 1);
  getDatas();
  getPositionBOList();
  // 处理 全选
  let checkedData = [];
  console.log(555, equipmentList.value);
  equipmentList.value.forEach(item => {
    checkedData.push(item.checked);
  });
  console.log(4444, checkedData);
  let flag = false;
  let result = checkedData.every(item => item === flag);
  console.log(777, result);
  if (result) {
    indeterminate.value = false;
    isAllChecked.value = false;
  } else if (checkedData.indexOf(false) !== -1) {
    isAllChecked.value = false;
    indeterminate.value = true;
  } else {
    isAllChecked.value = true;
    indeterminate.value = false;
  }
}
function editData() {
  console.log('草稿箱发布', route.query.infoType);
  if (route.query.infoType * 1 === 3) {
    // 文章
    getInfoArticle(route.query.id).then(res => {
      let data = res.data.data;
      editParams.value = {
        infoBO: data.infoVO,
        // 文章信息
        articleBO: data.articleVO,
        positionBOList: data.positionVOList,
        enclosureBOList: data.enclosureVOList // 附件信息
      };
      editParams.value.infoBO.id = null;
      editParams.value.articleBO.id = null;
    });
  } else {
    // 图像
    getInfoImage(route.query.id).then(res => {
      let documentVO = [];
      let datas = res.data.data;
      datas.imageVideoVOList.forEach(item => {
        documentVO.push({
          coverUrl: item.coverUrl,
          fileUrl: item.fileUrl,
          fileSize: item.fileSize,
          type: item.fileUrl.substr(item.fileUrl.length - 1, 1) === '4' ? 1 : 0 // 0 图片 1 视频
        });
      });
      editParams.value = {
        infoBO: {
          thumbnailUrl: datas.infoVO.thumbnailUrl,
          imageVideoBOList: documentVO,
          infoType: Number(route.query.infoType),
          isDraft: 0,
          infoName: datas.infoVO.infoName,
          infoDesc: datas.infoVO.infoDesc,
          infoTimeType: datas.infoVO.infoTimeType,
          infoDuration: datas.infoVO.infoDuration
        }
      };
    });
  }
}
const activeKey = ref('1');
const timingData = ref({});
const timingState = ref('');
//  位置参数
let positionBOList = ref([]);
// 离线确定按钮
function offLineDialogOk() {
  offLineDialog.determineBtn = true;
  offLineDialog.visible = false;
  getReleaseData(valueNum.value);
}
// 离线取消按钮
function offLineDialogCancel() {
  offLineDialog.determineBtn = true;
  offLineDialog.visible = false;
}
// 离线返回修改按钮
function offLineHandleOther() {
  offLineDialog.determineBtn = true;
  offLineDialog.visible = false;
}
// 转换时间戳
function getTimeFormat(timeS) {
  let time = new Date(timeS).getTime(); // 除1000 是变成秒级的时间戳 不除就是毫秒级
  return time;
}
// 发布位置事件
let valueNum = ref(); // 发布 定时发布值
function onPosition(value) {
  console.log(value);
  valueNum.value = value;
  // 1： 发布  2： 定时发布  8： 下一步
  if (equipmentValue.value.length === 0 && activeKey.value !== '3') {
    Message.warning('当前未选择设备');
    return;
  }
  if (patternState.value === 0) {
    if (moduleValue.value.length === 0 && activeKey.value !== '3') {
      Message.warning('当前未选择功能模块');
      return;
    }
  }
  if (activeKey.value === '3') {
    if (TypeinfoType.value === 0 || TypeinfoType.value === 1 || TypeinfoType.value === 2) {
      Message.warning('应用平台不能为空');
      return;
    }
  }
  let idData = [];
  console.log(positionBOList.value);
  console.log(666, funcModules.value);
  positionBOList.value.forEach(item => {
    // 如果是13（图像）就不能跟 4（文章） 12（图书） 11（资讯） 一起发送
    idData.push(item.widgetId * 1 === 13 ? 13 : 4);
  });
  console.log(idData);
  console.log(isAllEqual(idData));
  if (patternState.value === 0) {
    if (isAllEqual(idData)) {
      if (outPositionBOList.value.length !== 0) {
        offLineDialog.visible = true;
      } else {
        getReleaseData(value); //
      }
    } else {
      Message.warning('无法选择不同类型内容进行发布');
    }
  } else {
    let idList = [];
    funcModules.value.forEach(item => {
      if (item.checked) idList.push(item.widgetId * 1 === 13 ? 13 : 4);
    });
    // 霸屏模式下如果 有选择功能模块（不同类型提示， 共同类型往吓走）
    if (idList.length !== 0) {
      console.log(1);
      if (!isAllEqual(idList)) {
        console.log(2);
        Message.warning('无法选择不同类型内容进行发布');
      } else {
        if (outPositionBOList.value.length !== 0) {
          console.log(4);
          offLineDialog.visible = true;
        } else {
          console.log(5);
          getReleaseData(value); //
        }
      }
    } else {
      console.log(3);
      if (outPositionBOList.value.length !== 0) {
        console.log(4);
        offLineDialog.visible = true;
      } else {
        console.log(5);
        getReleaseData(value); //
      }
    }
  }
}
// 判断发布类型 是否相同
function isAllEqual(array) {
  if (array.length > 0) {
    return !array.some(function (value, index) {
      return value !== array[0];
    });
  } else {
    return true;
  }
}
let regularReleaseChild = ref(null);
// 发布执行方法
function getReleaseData(value) {
  console.log('getReleaseData', value);
  if (value === 1) {
    if (route.query.state === '编辑') {
      let params = postionData.value;
      if (params.infoBO.isForever === 1) {
        permanentChecked.value = true;
      } else {
        permanentChecked.value = false;
      }
      if (params.infoBO.releaseOpportunityType === 0) {
        //  普通发布0 定时发布1
        publishEndDate.value = params.infoBO.validPeriodStop;
        publishStartDate.value = params.infoBO.validPeriodStart;
        publishTime.value = [
          dayjs(params.infoBO.validPeriodStart.substring(0, 16), 'YYYY-MM-DD HH:mm'),
          dayjs(params.infoBO.validPeriodStop.substring(0, 16), 'YYYY-MM-DD HH:mm')
        ];
        // 时间差的毫秒数
        timeFn.value = timeFns(
          getTimeFormat(params.infoBO.validPeriodStart),
          getTimeFormat(params.infoBO.validPeriodStop)
        );
      } else {
        permanentChecked.value = false;
        publishEndDate.value = '';
        publishStartDate.value = '';
      }
    }
    publishDialog.visible = true;
  } else if (value === 2) {
    if (route.query.state === '编辑') {
      timingData.value = informationData.value;
      timingState.value = '1';
      regularReleaseChild.value.getDatas(timingData.value, '1');
    }
    regularRelease.value.visible = true;
  } else {
    console.log('zh sdf', positionBOList.value);
    console.log('tryrty', funcModules.value);
    if (patternState.value === 0) {
      console.log(1111);
      console.log(4444, activeKey.value);
      // 正常模式
      if (activeKey.value !== '3') {
        let idData = [];
        positionBOList.value.forEach(item => {
          idData.push(item.widgetId);
          // widgetId 4通知 11动态 12图书 13图像
          if (item.widgetId === 13) {
            // 图像
            toWhereTist.value = [tuxiangTitle.value];
            activeTab.value = 1;
            current.value = 1;
            releaseInfoList();
          } else {
            // 4通知 11动态 12图书
            toWhereTist.value = [wenzhangTitle.value];
            activeTab.value = 3;
            current.value = 1;
            releaseInfoList();
          }
        });
      } else {
        // 富文本
        toWhereTist.value = [wenzhangTitle.value];
        activeTab.value = 3;
        current.value = 1;
        releaseInfoList();
      }
    } else {
      console.log(33333);
      // 霸屏模式 如果不选择功能模块， 可以选择发布图像， 视频；如果选择功能模块只能对应相应的类型
      let idList = []; // 复制过来的 有部分重复 可以提出来
      funcModules.value.forEach(item => {
        if (item.checked) idList.push(item.widgetId * 1 === 13 ? 13 : 4);
      });
      if (idList.length !== 0) {
        positionBOList.value.forEach(item => {
          // widgetId 4通知 11动态 12图书 13图像
          if (item.widgetId === 13) {
            // 图像
            toWhereTist.value = [tuxiangTitle.value];
            activeTab.value = 1;
            current.value = 1;
            releaseInfoList();
          } else {
            // 4通知 11动态 12图书
            toWhereTist.value = [wenzhangTitle.value];
            activeTab.value = 3;
            current.value = 1;
            releaseInfoList();
          }
        });
      } else {
        toWhereTist.value = [wenzhangTitle.value, tuxiangTitle.value];
        activeTab.value = 2;
        current.value = 1;
        releaseInfoList();
      }
    }
    dialog.visible = true;
  }
}
let validPeriodStart = ref(''); // 定时发布有效开始时间
let validPeriodStop = ref(''); // 定时发布有效结束时间
let applicationData = ref([
  // 应用平台数据
  {
    equipmentTypeName: '泉城e学',
    equipmentTypeId: '999',
    positionType: 2,
    funcModule: 1,
    name: '泉城e学',
    positionId: '11111111',
    funcModuleName: '通知信息'
  }
]);
// 定时发布确定按钮
function regularReleaseOk(data) {
  console.log(data);
  validPeriodStart.value = data.validPeriodStart; // 有效期开始
  validPeriodStop.value = data.validPeriodStop; // 有效期结束
  if (data.isForever === false) {
    if (data.validPeriodStart === '' || data.validPeriodStop === '') {
      Message.warning('请选择有效期限');
      return;
    }
    if (data.releaseFrequency === 0) {
      if (data.daySiteBOList.length === 0) {
        Message.warning('至少选择一个发布时间');
        return;
      }
    } else {
      if (data.weekSiteBOList.length === 0) {
        Message.warning('至少选择一个发布时间');
        return;
      }
    }
  } else {
    if (data.releaseFrequency === 0) {
      if (data.daySiteBOList.length === 0) {
        Message.warning('至少选择一个发布时间');
        return;
      }
    } else {
      if (data.weekSiteBOList.length === 0) {
        Message.warning('至少选择一个发布时间');
        return;
      }
    }
  }
  if (route.query.state === '设备') {
    // 先选择设备 再选择草稿箱内容定时发布
    draftsParams.value.infoBO.validPeriodStart = data.validPeriodStart; // 有效期开始
    draftsParams.value.infoBO.validPeriodStop = data.validPeriodStop; // 有效期结束
    draftsParams.value.infoBO.releaseFrequency = data.releaseFrequency; // 发布频率 0每天 1每周
    draftsParams.value.infoBO.isForever = data.isForever ? 1 : 0; // 0非永久 1永久
    draftsParams.value.infoBO.releaseOpportunityType = data.releaseFrequency === 0 ? 1 : 2; // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null
    if (data.releaseFrequency === 0) {
      draftsParams.value.infoBO.daySiteBOList = data.daySiteBOList; // 按天发布 数组
    } else {
      draftsParams.value.infoBO.weekSiteBOList = data.weekSiteBOList; // 按周的定时发布 数组
    }
    if (activeKey.value === '3') {
      draftsParams.value.positionBOList = applicationData.value;
    } else {
      draftsParams.value.positionBOList = positionBOList.value;
    }
    conflictData.value = draftsParams.value.positionBOList;
    deviceConflict(draftsParams.value, 1, draftsParams.value.infoBO.infoType, '设备');
  } else if (route.query.state === '草稿箱发布') {
    // 草稿箱发布 进入设备发布
    editParams.value.infoBO.id = route.query.id;
    editParams.value.infoBO.isDraft = 1;
    editParams.value.infoBO.validPeriodStart = data.validPeriodStart; // 有效期开始
    editParams.value.infoBO.validPeriodStop = data.validPeriodStop; // 有效期结束
    editParams.value.infoBO.releaseFrequency = data.releaseFrequency; // 发布频率 0每天 1每周
    editParams.value.infoBO.isForever = data.isForever ? 1 : 0; // 0非永久 1永久
    editParams.value.infoBO.releaseOpportunityType = data.releaseFrequency === 0 ? 1 : 2; // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null
    if (data.releaseFrequency === 0) {
      editParams.value.infoBO.daySiteBOList = data.daySiteBOList; // 按天发布 数组
    } else {
      editParams.value.infoBO.weekSiteBOList = data.weekSiteBOList; // 按周的定时发布 数组
    }
    if (activeKey.value === '3') {
      editParams.value.positionBOList = applicationData.value;
    } else {
      editParams.value.positionBOList = positionBOList.value;
    }
    conflictData.value = editParams.value.positionBOList;
    deviceConflict(editParams.value, 1, Number(route.query.infoType), '设备');
  } else {
    let params = informationData.value;
    let modularType = params.infoBO.infoType; // 模块类型 0视频，1组图，2文档, 3文章
    params.infoBO.validPeriodStart = data.validPeriodStart; // 有效期开始
    params.infoBO.validPeriodStop = data.validPeriodStop; // 有效期结束
    params.infoBO.isForever = data.isForever ? 1 : 0; // 0非永久 1永久
    params.infoBO.releaseOpportunityType = data.releaseFrequency === 0 ? 1 : 2; // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null
    params.infoBO.releaseFrequency = data.releaseFrequency; // 发布频率 0每天 1每周
    if (data.releaseFrequency === 0) {
      params.infoBO.daySiteBOList = data.daySiteBOList; // 按天发布 数组
    } else {
      params.infoBO.weekSiteBOList = data.weekSiteBOList; // 按周的定时发布 数组
    }
    if (params.oldPositionBOList) {
      oldLists.value = params.oldPositionBOList; // 获取旧参数
    }
    if (activeKey.value === '3') {
      params.positionBOList = applicationData.value;
    } else {
      params.positionBOList = positionBOList.value;
    }
    params.daySiteVOList = [];
    params.weekSiteVOList = [];
    conflictData.value = params.positionBOList;
    deviceConflict(params, 1, modularType, route.query.state);
  }
  regularRelease.value.visible = false;
}
async function InterfaceFn(params, modularType, state) {
  console.log(555, params, modularType, state);
  params.infoBO.pattern = patternState.value; // ( 0普通模式 1霸屏模式);
  // 模块类型 1图像, 3文章
  let res;
  if (modularType * 1 === 1) {
    loading.value = true;
    if (state === '编辑') {
      console.log('old', oldLists.value);
      params.oldPositionBOList = oldLists.value;
      res = await updateInfoImage(params);
    } else {
      if (route.query.state === '重新发布') {
        params.infoBO.isDraft = 2;
        params.infoBO.id = route.query.id;
      }
      console.log('参数', params);
      res = await saveInfoImage(params);
    }
  } else {
    loading.value = true;
    if (state === '编辑') {
      console.log('old', oldLists.value);
      params.oldPositionBOList = oldLists.value;
      res = await updateInfoArticle(params);
    } else {
      console.log('保存参数', params);
      if (route.query.state === '重新发布') {
        params.infoBO.isDraft = 2;
        params.infoBO.id = route.query.id;
      }
      console.log('参数', params);
      res = await saveInfoArticle(params);
    }
  }
  console.log(res);
  if (res.data.code === 200) {
    loading.value = false;
    Message.success('发布成功');
    toIndex();
  } else {
    loading.value = false;
    Message.error('系统内部异常');
  }
}
// 发布提示确定
function publishTipsDialogOk() {
  publishTipsDialog.visible = false;
  deviceConflicParams.value.positionBOList = conflictData.value;
  deviceConflicParams.value.oldPositionBOList = oldList.value;
  InterfaceFn(deviceConflicParams.value, deviceConflicModularType.value, deviceConflicState.value);
}
// 发布提示取消
function publishTipsDialogCancel() {
  offLineDialog.determineBtn = true;
  publishTipsDialog.determineBtn = true;
  publishTipsDialog.visible = false;
}
// 发布提示返回修改
function publishTipsDialogOther() {
  publishTipsDialog.visible = false;
  offLineDialog.determineBtn = true;
  publishTipsDialog.determineBtn = true;
  if (route.query.state === '设备') {
    dialog.visible = true;
  }
}
// 下一步弹窗取消
function dialogCancel() {
  dialog.visible = false;
  activeTabs.value = '1';
}
// 下一步弹窗定时发布
function handleOk() {
  let checkedData = [];
  let data = [];
  draftsData.value.forEach(item => {
    if (item.checked) {
      checkedData.push(item.checked);
      data.push(item);
    }
  });
  if (checkedData.length !== 0) {
    dialog.visible = false;
    getDraftsDetails(data[0].infoType, data[0].id);
    publishDialog.visible = true; // 发布设置
  } else {
    Message.error('请选择一个草稿箱内容');
  }
}
// 获得各个模块草稿箱详情
async function getDraftsDetails(infoType, id) {
  if (infoType === 1) {
    // 图像
    await infoImageId(infoType, id).catch(res => {
      draftsParams.value = res;
    });

    console.log(draftsParams.value, 8989898);
  } else {
    // 文章
    await articleId(id).catch(res => {
      draftsParams.value = res;
    });
  }
}
// 下一步弹窗发布
function handleOther() {
  let checkedData = [];
  let data = [];
  draftsData.value.forEach(item => {
    if (item.checked) {
      checkedData.push(item.checked);
      data.push(item);
    }
  });
  if (checkedData.length !== 0) {
    dialog.visible = false;
    getDraftsDetails(data[0].infoType, data[0].id);
    regularRelease.value.visible = true;
  } else {
    Message.error('请选择一个草稿箱内容');
  }
}

// 发布设置取消按钮
function publishDialogCancel() {
  publishDialog.visible = false;
  if (route.query.state === '设备') {
    dialog.visible = true;
  }
  permanentChecked.value = false;
  publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
  timeFn.value = '0天0时0秒';
}
// 发布设置发布按钮
function publishDialogOk() {
  if (permanentChecked.value === false && publishEndDate.value === '') {
    Message.error('时长不能为空');
    return;
  }
  console.log(99999, route.query.state);
  if (route.query.state === '设备') {
    // 先选择设备 再选择草稿箱内容发布
    draftsParams.value.infoBO.validPeriodStart = moment().format('YYYY-MM-DD HH:mm:ss'); // 有效期开始
    if (permanentChecked.value) {
      draftsParams.value.infoBO.validPeriodStop = '9999-12-31 23:59:59'; // 有效期结束
    } else {
      draftsParams.value.infoBO.validPeriodStop =
        publishEndDate.value.length === 16 ? publishEndDate.value + ':00' : publishEndDate.value;
    }
    draftsParams.value.infoBO.isForever = permanentChecked.value ? 1 : 0; // 0非永久 1永久
    draftsParams.value.infoBO.releaseOpportunityType = 0; // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null
    if (activeKey.value === '3') {
      draftsParams.value.positionBOList = applicationData.value;
    } else {
      draftsParams.value.positionBOList = positionBOList.value;
    }
    conflictData.value = draftsParams.value.positionBOList;
    if (activeKey.value === '3') {
      InterfaceFn(draftsParams.value, draftsParams.value.infoBO.infoType, '设备');
    } else {
      deviceConflict(draftsParams.value, 0, draftsParams.value.infoBO.infoType, '设备');
    }
  } else if (route.query.state === '草稿箱发布') {
    editParams.value.infoBO.id = route.query.id;
    editParams.value.infoBO.isDraft = 1;
    editParams.value.infoBO.validPeriodStart = moment().format('YYYY-MM-DD HH:mm:ss'); // 有效期开始
    if (permanentChecked.value) {
      editParams.value.infoBO.validPeriodStop = '9999-12-31 23:59:59'; // 有效期结束
    } else {
      editParams.value.infoBO.validPeriodStop =
        publishEndDate.value.length === 16 ? publishEndDate.value + ':00' : publishEndDate.value;
    }
    editParams.value.infoBO.isForever = permanentChecked.value ? 1 : 0; // 0非永久 1永久
    editParams.value.infoBO.releaseOpportunityType = 0; // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null

    if (activeKey.value === '3') {
      editParams.value.positionBOList = applicationData.value;
    } else {
      editParams.value.positionBOList = positionBOList.value;
    }
    conflictData.value = editParams.value.positionBOList;
    if (activeKey.value === '3') {
      InterfaceFn(editParams.value, Number(route.query.infoType), '设备');
    } else {
      deviceConflict(editParams.value, 0, Number(route.query.infoType), '设备');
    }
  } else if (route.query.state === '草稿箱修改') {
    let params = informationData.value;
    let modularType = params.infoBO.infoType; // 模块类型 0视频，1组图，2文档, 3文章
    if (permanentChecked.value) {
      params.infoBO.validPeriodStart = moment().format('YYYY-MM-DD HH:mm:ss'); // 有效期开始
      // 有效期结束
      params.infoBO.validPeriodStop = '9999-12-31 23:59:59';
    } else {
      params.infoBO.validPeriodStart = publishStartDate.value + ':00'; // 有效期开始
      params.infoBO.validPeriodStop =
        publishEndDate.value.length === 16 ? publishEndDate.value + ':00' : publishEndDate.value;
    }
    params.infoBO.isForever = permanentChecked.value ? 1 : 0; // 0非永久 1永久
    params.infoBO.releaseOpportunityType = 0; // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null
    if (activeKey.value === '3') {
      params.positionBOList = applicationData.value; // 位置设备数据
      params.oldPositionBOList = [];
    } else {
      params.positionBOList = positionBOList.value; // 位置设备数据
      params.oldPositionBOList = [];
    }
    conflictData.value = params.positionBOList;
    if (activeKey.value === '3') {
      InterfaceFn(params, modularType, route.query.state);
    } else {
      deviceConflict(params, 0, modularType, route.query.state);
    }
  } else {
    // 走了新建 先内容->设备
    let params = informationData.value;
    console.log('获取的 发布内容数据', params);
    let modularType = params.infoBO.infoType; // 模块类型 0视频，1组图，2文档, 3文章
    if (params.oldPositionBOList) {
      oldLists.value = params.oldPositionBOList; // 获取旧参数
    }
    if (permanentChecked.value) {
      params.infoBO.validPeriodStart = moment().format('YYYY-MM-DD HH:mm:ss'); // 有效期开始
      // 有效期结束
      params.infoBO.validPeriodStop = '9999-12-31 23:59:59';
    } else {
      params.infoBO.validPeriodStart =
        publishStartDate.value.length === 19
          ? publishStartDate.value
          : publishStartDate.value + ':00'; // 有效期开始
      params.infoBO.validPeriodStop =
        publishEndDate.value.length === 16 ? publishEndDate.value + ':00' : publishEndDate.value;
    }
    params.infoBO.isForever = permanentChecked.value ? 1 : 0; // 0非永久 1永久
    params.infoBO.releaseOpportunityType = 0; // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null
    console.log('发布位置数据', positionBOList.value);
    if (positionBOList.value.length === 0) {
      if (activeKey.value === '3') {
        params.positionBOList = applicationData.value; // 位置设备数据
        params.oldPositionBOList = [];
      } else {
        params.positionBOList = positionBOList.value; // 位置设备数据
        params.oldPositionBOList = [];
      }
      conflictData.value = params.positionBOList;
      if (activeKey.value === '3') {
        InterfaceFn(params, modularType, route.query.state);
      } else {
        deviceConflict(params, 0, modularType, route.query.state);
      }
    } else {
      if (activeKey.value === '3') {
        params.positionBOList = applicationData.value;
        params.oldPositionBOList = [];
      } else {
        params.positionBOList = positionBOList.value; // 位置设备数据
        let newId = [];
        let oldId = [];
        console.log('参数--带设备', params);
        // 新建应该没有 oldPositionBOList
        if (params.oldPositionBOList) {
          params.oldPositionBOList.forEach(item => {
            oldId.push(item.funcModule * 1);
          });
        }
        positionBOList.value.forEach(item => {
          newId.push(item.funcModule * 1);
        });
        if (newId.toString() === oldId.toString()) {
          params.oldPositionBOList = [];
        }
      }
      oldList.value = params.oldPositionBOList;
      conflictData.value = params.positionBOList;
      if (activeKey.value === '3') {
        InterfaceFn(params, modularType, route.query.state);
      } else {
        deviceConflict(params, 0, modularType, route.query.state);
      }
    }
    console.log('参数', params);
  }
  publishDialog.visible = false;
  // 发布时长清空
  permanentChecked.value = false;
  publishTipsDialog.determineBtn = true;
  publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
  timeFn.value = '0天0时0秒';
}
let oldList = ref([]);
let oldLists = ref([]);
let conflictDevice = ref([]); // 冲突设备list
// 发布冲突检查
let deviceConflicParams = ref(); // 发布冲突参数
let deviceConflicModularType = ref(); // 发布冲突类型
let deviceConflicState = ref(); // 发布冲突状态
function deviceConflict(params, opportunityType, modularType, state) {
  deviceConflicParams.value = params;
  deviceConflicModularType.value = modularType;
  deviceConflicState.value = state;
  // 发布参数
  let equipmentIdList = []; // 设备id 集合
  if (positionBOList.value.length === 0) {
    let paramss = informationData.value;
    paramss.oldPositionBOList.forEach(item => {
      equipmentIdList.push(item.positionId);
    });
  } else {
    positionBOList.value.forEach(item => {
      equipmentIdList.push(item.positionId);
    });
  }
  let releaseParamss = {
    current: 1,
    size: 10,
    data: {
      pattern: patternState.value,
      infoType: route.query.releaseType === '4' ? 3 : route.query.releaseType === '13' ? 1 : 2, // 1图像（视频+组图）   2文档  3文章
      validPeriodStart: moment().format('YYYY-MM-DD HH:mm:ss'),
      validPeriodStop: publishEndDate.value + ':00',
      equipmentIdList: equipmentIdList,
      opportunityType: opportunityType,
      isForever: permanentChecked.value ? 1 : 0
    }
  };
  // 定时发布参数
  let timeParams = {
    current: 1,
    size: 10,
    data: {
      pattern: patternState.value,
      infoType: route.query.releaseType === '4' ? 3 : route.query.releaseType === '13' ? 1 : 2, // 1图像（视频+组图）   2文档  3文章
      validPeriodStart: validPeriodStart.value,
      validPeriodStop: validPeriodStop.value,
      equipmentIdList: equipmentIdList,
      opportunityType: opportunityType,
      isForever: permanentChecked.value ? 1 : 0,
      frequency: params.infoBO.releaseFrequency, // 频率 0 天 1 周
      byWeekList: params.infoBO.releaseFrequency === 1 ? params.infoBO.weekSiteBOList : [], // 周
      byDayList: params.infoBO.releaseFrequency === 0 ? params.infoBO.daySiteBOList : [] // 天
    }
  };
  if (permanentChecked.value) {
    releaseParamss.data.validPeriodStop = '9999-12-31 23:59:59';
  } else {
    releaseParamss.data.validPeriodStop =
      publishEndDate.value.length === 16 ? publishEndDate.value + ':00' : publishEndDate.value;
  }
  console.log('霸屏');
  checkCollide(opportunityType === 0 ? releaseParamss : timeParams).then(res => {
    // 未返回数据 代表没有冲突设备
    if (res.data.data.records.length === 0) {
      InterfaceFn(params, modularType, state);
    } else {
      // 打开设备冲突 弹窗
      console.log('郭亚山', res.data.data);
      conflictDevice.value = res.data.data.records;
      publishTipsDialog.visible = true;
    }
  });
}
// 跳转相应模块
function toContent(index) {
  toWhereTist.value.forEach(item => {
    item.active = false;
  });
  toWhereTist.value[index].active = true;
  let data = []; // 正常模式数据
  if (activeKey.value === '3') {
    data = JSON.stringify(applicationData.value);
  } else {
    data = JSON.stringify(positionBOList.value);
  }
  console.log('位置数据', data);
  localStorage.setItem('postionData', data);
  console.log(localStorage.getItem('informationData'), 99999);
  if (localStorage.getItem('informationData')) {
    localStorage.setItem('informationData', localStorage.getItem('informationData'));
  }
  // store.commit('addCacheRoute', 'postMessage');
  store.commit('addCacheRoute', 'postion');
  router.push({
    path: toWhereTist.value[index].path,
    query: {
      patternState: patternState.value, // 是否是霸屏
      activeState: toWhereTist.value[index].id,
      state: 'device'
    }
  });
  dialog.visible = false;
}
let timeFn = ref('0天0时0秒');
// 时间框事件
function openChange(e) {
  if (e) {
    publishTime.value = [
      dayjs(moment().format('YYYY-MM-DD HH:mm')),
      dayjs(moment().format('YYYY-MM-DD HH:mm'))
    ];
    publishStartDate.value = moment().format('YYYY-MM-DD HH:mm');
  } else {
    if (publishEndDate.value === '') {
      publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
    } else {
      publishTime.value = [
        dayjs(moment().format('YYYY-MM-DD HH:mm')),
        dayjs(publishEndDate.value, 'YYYY-MM-DD HH:mm')
      ];
    }
  }
  if (publishEndDate.value !== '') {
    timeFn.value = timeFns(
      getTimeFormat(publishStartDate.value),
      getTimeFormat(publishEndDate.value)
    );
  }
}
function selsectTime(date, dateString) {
  publishStartDate.value = dateString[0];
  publishEndDate.value = dateString[1];
  disabledDateTime();
}
// 事件确认事件
function ok(date) {
  timeFn.value = timeFns(
    getTimeFormat(publishStartDate.value),
    getTimeFormat(publishEndDate.value)
  );
  let newS = moment(publishTime.value[1].$d).format('YYYY-MM-DD HH:mm'); // 选择的时间
  let currentDate = moment().format('YYYY-MM-DD HH:mm');
  if (newS <= currentDate) {
    Message.error('结束时间不能小于等于开始时间,请重新选择结束时间');
    publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), null];
    publishEndDate.value = '';
    timeFn.value = '0天0时0秒';
  }
}
</script>
<style lang="less" scoped>
@import './index.less';
</style>
